package com.jianan.mis.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import sun.net.TelnetInputStream;
import sun.net.TelnetOutputStream;
import sun.net.ftp.FtpClient;

public class FtpUtils {

	private String server;
	private String user;
	private String password;
	private String ftpPath;

	public void download(String filePath, String fileName) {
		try {
			FtpClient ftpClient = new FtpClient();
			ftpClient.openServer(server);
			ftpClient.login(user, password);
			if (ftpPath.length() != 0)
				ftpClient.cd(ftpPath);
			ftpClient.binary();
			TelnetInputStream is = ftpClient.get(fileName);
			File fileOut = new File(filePath);
			FileOutputStream os = new FileOutputStream(fileOut);
			byte[] bytes = new byte[1024];
			int c;
			while ((c = is.read(bytes)) != -1) {
				os.write(bytes, 0, c);
			}
			is.close();
			os.close();
			ftpClient.closeServer();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}

	public void upload(String filePath, String fileName) {
		try {
			FtpClient ftpClient = new FtpClient();
			ftpClient.openServer(server);
			ftpClient.login(user, password);
			if (ftpPath.length() != 0)
				ftpClient.cd(ftpPath);
			ftpClient.binary();
			TelnetOutputStream os = ftpClient.put(fileName);
			File fileIn = new File(filePath);
			FileInputStream is = new FileInputStream(fileIn);
			byte[] bytes = new byte[1024];
			int c;
			while ((c = is.read(bytes)) != -1) {
				os.write(bytes, 0, c);
			}
			is.close();
			os.close();
			ftpClient.closeServer();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}

	public void setFtpPath(String ftpPath) {
		this.ftpPath = ftpPath;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public void setServer(String server) {
		this.server = server;
	}

	public void setUser(String user) {
		this.user = user;
	}
}
